import axios from 'axios'
import uniappAdapter from './adapter/index.js'
import { apiUrl } from "@/common/api/url.js"
import errorInterceptor from './error-hander.js'

//创建axios实例
const instance = axios.create({
  adapter: uniappAdapter,
  timeout: 10000,
  headers: { "Content-Type": "application/json" },
  baseURL: apiUrl,
  authType: false
})

//请求拦截器
const requestInterceptor = (config) => {
  uni.showLoading({mask: true})
  //header添加token
  if (config.authType) {
    const token = uni.getStorageSync('token')
    if (!token) {
      throw new axios.Cancel('no token !')
      //转登录
    }
    config.headers.Authorization = 'Bearer ' + token
  }
  return config
}

//响应拦截器
const responseInterceptor = (response) => {
  uni.hideLoading()
  return response
}

instance.interceptors.request.use(requestInterceptor, errorInterceptor(instance))
instance.interceptors.response.use(responseInterceptor, errorInterceptor(instance))
export default instance
